package com.wydstation.power.collection;

import com.ghgande.j2mod.modbus.Modbus;
import com.ghgande.j2mod.modbus.facade.ModbusSerialMaster;
import com.ghgande.j2mod.modbus.util.SerialParameters;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.common.serialization.ByteArraySerializer;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;


public class Server {
    private static final ModbusSerialMaster master;
    private static final KafkaProducer producer;

    static {
        SerialParameters parameters = new SerialParameters();
        parameters.setPortName("COM6");
        parameters.setOpenDelay(1000);
        parameters.setEncoding(Modbus.SERIAL_ENCODING_RTU);
        parameters.setBaudRate(9600);
        parameters.setStopbits(1);
        master = new ModbusSerialMaster(parameters);
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "localhost:9092");
        properties.setProperty("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");       // 键的序列化
        properties.setProperty("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");  // 值的序列化
//        properties.setProperty("value.serializer", "com.wydstation.power.collection.MyValueSerializer");  // 值的序列化
        properties.setProperty("group.id", "modbus-1");
        properties.setProperty("client.id", "zhang_test1");
        properties.setProperty("auto.offset.reset", "earliest");
        properties.setProperty("enable.auto.commit", "false");
        producer = new KafkaProducer(properties);
        try {
            master.connect();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public static void main(String[] args) throws Exception {

        StationInfoContext context = new StationInfoContext(master, producer);
        List<UnitItem> list = new ArrayList<>();
        UnitItem item = new UnitItem();
        item.setUnidId(1);
        item.setStartAddress(0);
        item.setType(4);
        item.setCount(125);
        item.setDeviceId("1");
        item.setLimit(125);

        list.add(item);
        context.setUnitList(list);
        ScheduledThreadPoolExecutor scheduledExecutor = new ScheduledThreadPoolExecutor(Runtime.getRuntime().availableProcessors());
        scheduledExecutor.scheduleAtFixedRate(() -> {
            try {
                context.run();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }, 1, 1, TimeUnit.SECONDS);

    }


}
